package kunsch.bdd.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import kunsch.bdd.AbstractBDD;
import kunsch.bdd.AbstractNode;

public class DOTCreator
{

	BufferedWriter writer;

	public DOTCreator()
	{

	}

	public void createDotPngFile(String dotExePath, File dotFile, String pathname)
	{

		File pngFile = new File(pathname);

		String[] args =
		{ dotExePath, "-Tpng", dotFile.getAbsolutePath(), "-o", pngFile.getAbsolutePath() };

		try
		{

			Process p = Runtime.getRuntime().exec(args);
			p.waitFor();

		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		catch (InterruptedException e)
		{
			e.printStackTrace();
		}

	}

	public File createDotFile(AbstractBDD bdd, String filepath)
	{

		File file = null;

		try
		{
			file = new File(filepath);
			file.createNewFile();
			writer = new BufferedWriter(new FileWriter(file));

			writer.write("digraph Beziehungen {");
			writer.newLine();
			writer.write("nodesep=0.7");
			writer.newLine();

			writeLabels(bdd.getNodes());
			writePaths(bdd.getNodes());

			writer.write("}");

			writer.flush();
			writer.close();

		}
		catch (IOException e)
		{
			e.printStackTrace();
		}

		return file;

	}

	private void writeLabels(List<AbstractNode> abstractNodes) throws IOException
	{

		for (AbstractNode abstractNode : abstractNodes)
		{

			int id = System.identityHashCode(abstractNode);
			writer.write(id + "[label=\"" + abstractNode.getDescription()  + "\"];");
			writer.newLine();

		}

	}

	private void writePaths(List<AbstractNode> abstractNodes) throws IOException
	{

		for (AbstractNode abstractNode : abstractNodes)
		{

			if (abstractNode.getOneChild() != null && abstractNode.getZeroChild() != null)
			{

				int id = System.identityHashCode(abstractNode);
				int oneId = System.identityHashCode(abstractNode.getOneChild());
				int zeroId = System.identityHashCode(abstractNode.getZeroChild());

				writer.write(id + " -> " + oneId + "[label=\"1\"];");
				writer.newLine();
				writer.write(id + " -> " + zeroId + "[label=\"0\",style=dashed];");
				writer.newLine();
			}
		}

	}
}
